import { Navigator, View, ScrollView, Text, Image} from '@tarojs/components';
import Taro from '@tarojs/taro';
import Article from '../../component/article'
import withWeapp from '@tarojs/with-weapp';
import Panel from '../../component/panel';
import Page from "../../component/page";
import './index.scss'

const regeneratorRuntime = require('../../utils/async.js')

// require('../../utils/async.js')
//logs.js
const flow = require('../../utils/flow.js')
const modules = require('./module.js')
const app = Taro.getApp()

@withWeapp('Page')
class TagPage extends Taro.Component {
  state = {
    articles: {}
  }
  componentDidMount = async () => {
    this.flow = new flow(
      this,
      modules
    )
    const systemInfo = Taro.getSystemInfoSync()
    const { windowHeight, statusBarHeight } = systemInfo
    // header部分高度
    this.setState({  
      contentHeight: windowHeight - statusBarHeight - 43
    })

    const { tag } = this.$router.params;
    this.setState({ tagName: tag, defaultTagName: tag });

    await this.flow.dispatch('getTag', { name: tag })
    await this.flow.dispatch('getList', { key: tag });
  }
  back = () => {
    Taro.navigateBack({ url: "../index/index" });
  };
  follow = isFollow => e => {
    const { tag = {} } = this.state;
    tag.isFollowing = isFollow;
    this.setState({
      tag
    })
    this.flow.dispatch('saveTags', { 
      type: isFollow ? 'tags' : 'remove_tag',
      tags: [tag.name]
    })
  }

  onScrollToLower = (e) => {
    this.setState({
      downLoading: true,
      page: ++this.state.page
    }, () => {

      this.loadMore().then(() => {
        this.setState({ downLoading: false })
      }).catch(() => {
        // 失败之后
        Taro.showToast({ title: '数据加载失败', icon: 'none' })
        this.setState({
          downLoading: false,
          page: --this.state.page
        })
      })

    })
  }
  onLoadMore = async e => {
    // const { name } = e.target.dataset
    const { defaultTagName, articles } = this.state;
    const curTag = articles[defaultTagName];

    if (curTag.hasMore) {
      await this.flow.dispatch('loadMore', {
        key: defaultTagName,
        pageIndex: curTag.pageIndex + 1
      })
    }
  }
  render() {
    const { headerHeight } = app.globalData
    const { tag = {}, contentHeight } = this.state;
    const { img, brothers = [], desc, followerNumber, name, subs, parents, isFollowing } = tag;

    const {
      articles,
      defaultTagName
    } = this.state

    const current = articles[defaultTagName] || {};

    return (
      <View>
        <Page
          onClickLeftIcon={this.back}
          leftIconType="chevron-left"
          leftText="返回"
          title="标签"
          isPrevPadding={true}
        />
        <ScrollView
          className="page-container"
          scrollWithAnimation="true"
          onScrollToLower={this.onLoadMore}
          scrollY="true"
          style={`height: ${contentHeight - 10}px;margin-top: ${headerHeight + 5}px`}
        >
          <View className="tag-info-box">
            <View className="tag-info">
              <View className="tag-basic-box">
                <Image src={img} className="tag-basic-img"/>
                <View className="tag-basic">
                  <Text className="tag-name">
                    {name}
                  </Text>
                  <Text className="tag-user-name">{followerNumber}人关注</Text>
                </View>
              </View>
              {
                !isFollowing ? (
                  <View className="tag-addin" onClick={this.follow(true)}>+加入</View>
                ) : (
                  <View className="tag-addin followed" onClick={this.follow(false)}>已关注</View>
                )
              }
            </View>
            <View className="tag-brief">
              <Text style={{color: '#fff'}}>简介：</Text>
              {desc}
            </View>
          </View>
          <View className="app-panel">
            <View className="app-title">
              <Text>其它相关：</Text>
            </View>
            <View className="app-content">
              <ScrollView 
                scrollX={true}
                style={{display: 'flex', whiteSpace: 'nowrap'}}
              >
                {
                  brothers.map(tag => (
                    <Navigator 
                      style={{display: 'inline-flex'}}
                      url={`../tag-detail/index?tag=${tag.name}`}
                    >
                      <View className="app-tag">
                        <Image className="app-tag-img" src={tag.img} />
                        <Text className="app-tag-title">{tag.name}</Text>
                        <Text className="app-tag-tips">{tag.desc}</Text>
                      </View>
                    </Navigator>
                  ))
                }
              </ScrollView>
            </View>
          </View>
          <View className="app-panel">
            <View className="app-title">
              <Text>内容更新</Text>
              <Navigator url="" style={{ color: '#777', fontSize: '13px' }}></Navigator>
            </View>
            <View className="app-content">
              <View className="article-container">
                  {
                    current && current.articles && current.articles.map((article, index) => {
                      return <Article article={article} />
                    })
                  }
                  <View
                    className={
                      current.showLoading ? 'more-arts' : 'hide'
                    }
                  >
                    加载中...
                  </View>
                  <View
                    className={
                      current.hasMore ? 'hide' : 'no-more-arts'
                    }
                  >
                    --没有更多内容了--
                  </View>
                </View>
            </View>
          </View>
        </ScrollView>
      </View>
    )
  }
}

export default TagPage